package com.yld.car.common;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

import com.yld.car.domain.BaseColorInfo;
import com.yld.car.domain.Car;
import com.yld.car.domain.DealerBaseInfo;
import com.yld.car.domain.DetailInfoCar;
import com.yld.car.domain.DisplacementInfo;
import com.yld.car.domain.EditCarInfo;
import com.yld.car.domain.MyPublishCarInfo;
import com.yld.car.domain.SearchDetailCar;
import com.yld.car.domain.UserInfo;

public final class NetworkProgressUtils {

	private NetworkProgressUtils() {
	};

	private static final NetworkProgressUtils INSTANCE = new NetworkProgressUtils();

	public static NetworkProgressUtils getInstance() {

		return INSTANCE;
	}

	public Object getWebservicesByData(String nameSpace, String methodName,
			String soapAction, String baseUrl, HashMap<String, String> allParams) {

		// 创建SoapObject对象，指定命名空间和方法名，封装参数
		SoapObject soapObject = new SoapObject(nameSpace, methodName);
		// 创建信封序列化对象，封装SoapObject对象

		if (null != allParams) {

			Set<Map.Entry<String, String>> set = allParams.entrySet();

			Iterator<Map.Entry<String, String>> i = set.iterator();
			while (i.hasNext()) {

				Map.Entry<String, String> entry = i.next();
				soapObject.addProperty(entry.getKey(), entry.getValue());

			}
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapSerializationEnvelope.VER11);
		envelope.bodyOut = soapObject;
		envelope.dotNet = true;
		envelope.setOutputSoapObject(soapObject);

		// 创建传输对象，将信封序列化对象远程传输，并请求服务
		HttpTransportSE transport = new HttpTransportSE(baseUrl);

		try {
			transport.call(soapAction, envelope);

			System.out.println(envelope.bodyIn);

			SoapObject soap = (SoapObject) envelope.bodyIn;

			// System.out.println("soap==="+soap);
			SoapPrimitive p = (SoapPrimitive) soap.getProperty(0);
			// System.out.println("p===="+p);
			Object o = p.getValue();

			// System.out.println("o===>"+o);
			if (o != null) {
				return o;
			} else {
				return "";
			}
		} catch (HttpResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassCastException e) {

			e.printStackTrace();
		}

		return "exception";
	}

	public static final int BASE_CAR_TYPE = 1;
	public static final int SEARCH_CAR_TYPE = 2;
	public static final int DETAIL_INFO_CAR_TYPE = 3;
	public static final int MY_PUBLISH_CAR_INFO_TYPE = 4;

	public ArrayList<Car> parseJson(String json, String arrayName, int type,
			boolean isMyself) {

		ArrayList<Car> allCars = new ArrayList<Car>();
		try {
			JSONObject jsonObject = new JSONObject(json);

			JSONArray array = jsonObject.getJSONArray(arrayName);

			if (BASE_CAR_TYPE == type) {
				for (int i = 0; i < array.length(); i++) {

					jsonObject = (JSONObject) array.get(i);

					Car c = new Car();
					c.setId(jsonObject.getString("id"));
					c.setNo(jsonObject.getString("no"));
					c.setName(jsonObject.getString("name"));

					allCars.add(c);
				}

			} else if (SEARCH_CAR_TYPE == type) {

				// System.out.println("type=========="+jsonObject);
				for (int i = 0; i < array.length(); i++) {

					jsonObject = (JSONObject) array.get(i);

					SearchDetailCar s = new SearchDetailCar();
					s.setId(jsonObject.getString("id"));
					s.setNo(jsonObject.getString("no"));
					s.setName(jsonObject.getString("name"));
					s.setAdddate(jsonObject.getString("adddate"));
					s.setClassid(jsonObject.getString("classid"));
					s.setCompanyname(jsonObject.getString("companyname"));
					s.setGangkouname(jsonObject.getString("gangkouname"));
					s.setGhtime(jsonObject.getString("qhtime"));
					s.setPinpainame(jsonObject.getString("pinpainame"));
					s.setPress(jsonObject.getString("press"));
					s.setVin(jsonObject.getString("vin"));
					s.setXhorgh(jsonObject.getString("xhorqh"));
					s.setXiliename(jsonObject.getString("xiliename"));
					s.setXppz(jsonObject.getString("xppz"));
					s.setSummary("summary");
					s.setAuthor("author");
					if (isMyself) {
						// 添加dealerid字段
						s.setDealerid(jsonObject.getString("dealerid"));
					}

					allCars.add(s);
				}

			} else if (DETAIL_INFO_CAR_TYPE == type) {

				for (int i = 0; i < array.length(); i++) {

					jsonObject = (JSONObject) array.get(i);

					DetailInfoCar d = new DetailInfoCar();
					d.setId(jsonObject.getString("id"));
					d.setNo(jsonObject.getString("no"));
					d.setName(jsonObject.getString("name"));
					d.setAdddate(jsonObject.getString("adddate"));
					d.setCompanyname(jsonObject.getString("companyname"));
					d.setGhtime(jsonObject.getString("qhtime"));
					d.setPress(jsonObject.getString("press"));
					d.setVin(jsonObject.getString("vin"));
					d.setXppz(jsonObject.getString("xppz"));
					d.setImg(jsonObject.getString("img"));
					d.setDealerid(jsonObject.getString("dealerid"));
					d.setGuanzu(jsonObject.getString("guanzu"));
					d.setTelephone(jsonObject.getString("telephone"));
					d.setWsname(jsonObject.getString("wsname"));
					d.setNsname(jsonObject.getString("nsname"));
					allCars.add(d);
				}
			} else if (MY_PUBLISH_CAR_INFO_TYPE == type) {

				for (int i = 0; i < array.length(); i++) {

					jsonObject = (JSONObject) array.get(i);

					MyPublishCarInfo myPublishCarInfo = new MyPublishCarInfo();
					myPublishCarInfo.setId(jsonObject.getString("id"));
					myPublishCarInfo.setNo(jsonObject.getString("no"));
					myPublishCarInfo.setName(jsonObject.getString("name"));
					myPublishCarInfo
							.setAdddate(jsonObject.getString("adddate"));
					// myPublishCarInfo
					// .setClassid(jsonObject.getString("classid"));
					myPublishCarInfo.setCompanyname(jsonObject
							.getString("companyname"));
					myPublishCarInfo.setGangkouname(jsonObject
							.getString("gangkouname"));
					myPublishCarInfo.setGhtime(jsonObject.getString("qhtime"));
					myPublishCarInfo.setPinpainame(jsonObject
							.getString("pinpainame"));
					myPublishCarInfo.setPress(jsonObject.getString("press"));
					myPublishCarInfo.setVin(jsonObject.getString("vin"));
					// myPublishCarInfo.setXhorgh(jsonObject.getString("xhorqh"));
					myPublishCarInfo.setUserId(jsonObject.getString("userid"));
					myPublishCarInfo.setXiliename(jsonObject
							.getString("xiliename"));
					myPublishCarInfo.setXppz(jsonObject.getString("xppz"));
					allCars.add(myPublishCarInfo);
				}

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return allCars;
	}

	/**
	 * 获取网络类型
	 * 
	 * @param context
	 * @return
	 */
	public int getAPNType(Context context) {
		int netType = -1;
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			Log.e("networkInfo.getExtraInfo()",
					"networkInfo.getExtraInfo() is "
							+ networkInfo.getExtraInfo());
			if (networkInfo.getExtraInfo().toLowerCase()
					.equals(NET_STATE_VALUE)) {
				netType = CMNET;
			} else {
				netType = CMWAP;
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = WIFI;
		}
		return netType;
	}

	public static final int CMNET = 3;
	public static final int CMWAP = 2;
	public static final int WIFI = 1;
	public static final String NET_STATE_VALUE = "cmnet";

	public Bitmap downloadImage(String download_url) {

		try {
			URL url = new URL(download_url);

			InputStream inputStream = url.openStream();
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

			return bitmap;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public InputStream getImageStream(String download_url) {

		try {
			URL url = new URL(download_url);

			InputStream inputStream = url.openStream();
			return inputStream;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<BaseColorInfo> parseJsonColor(String json,
			String arrayName, boolean flag) {

		ArrayList<BaseColorInfo> allColors = new ArrayList<BaseColorInfo>();

		JSONObject jsonObject = null;
		JSONArray array = null;
		try {
			jsonObject = new JSONObject(json);
			array = jsonObject.getJSONArray(arrayName);

			for (int i = 0; i < array.length(); i++) {

				jsonObject = (JSONObject) array.get(i);

				BaseColorInfo b = new BaseColorInfo();
				b.setNo(jsonObject.getString("no"));
				b.setId(jsonObject.getString("id"));
				b.setDdname(jsonObject.getString("ddname"));
				if (flag) {
					b.setDdshortname(jsonObject.getString("ddshortname"));
				}

				allColors.add(b);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return allColors;
	}

	public ArrayList<BaseColorInfo> parseFindByFilterColor(String json,
			String arrayName) {

		ArrayList<BaseColorInfo> allColors = new ArrayList<BaseColorInfo>();

		JSONObject jsonObject = null;
		JSONArray array = null;
		try {
			jsonObject = new JSONObject(json);
			array = jsonObject.getJSONArray(arrayName);

			for (int i = 0; i < array.length(); i++) {

				jsonObject = (JSONObject) array.get(i);

				BaseColorInfo b = new BaseColorInfo();
				b.setNo(jsonObject.getString("no"));
				b.setId(jsonObject.getString("id"));
				b.setName(jsonObject.getString("name"));
				allColors.add(b);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return allColors;
	}

	public ArrayList<DisplacementInfo> parseJsonDisplacement(String json,
			String arrayName) {

		ArrayList<DisplacementInfo> allDisplacements = new ArrayList<DisplacementInfo>();

		JSONObject jsonObject = null;
		JSONArray array = null;
		try {
			jsonObject = new JSONObject(json);
			array = jsonObject.getJSONArray(arrayName);

			for (int i = 0; i < array.length(); i++) {

				jsonObject = (JSONObject) array.get(i);

				DisplacementInfo d = new DisplacementInfo();
				d.setNo(jsonObject.getString("no"));
				d.setId(jsonObject.getString("id"));
				d.setName(jsonObject.getString("name"));

				allDisplacements.add(d);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return allDisplacements;
	}

	public Object uploadImage(String nameSpace, String methodName,
			String soapAction, String baseUrl, HashMap<String, Object> allParams) {

		// 创建SoapObject对象，指定命名空间和方法名，封装参数
		SoapObject soapObject = new SoapObject(nameSpace, methodName);
		// 创建信封序列化对象，封装SoapObject对象

		if (null != allParams) {

			Set<Map.Entry<String, Object>> set = allParams.entrySet();

			Iterator<Map.Entry<String, Object>> i = set.iterator();
			while (i.hasNext()) {

				Map.Entry<String, Object> entry = i.next();
				if (entry.getValue() instanceof byte[]) {
					// System.out.println("test===>");
					byte[] cache = (byte[]) entry.getValue();
					String data = new String(Base64.encode(cache));
					try {
						FileWriter fos = new FileWriter(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/test.txt");

						fos.write(data);
						fos.flush();
						fos.close();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// System.out.println("image==="+data);
					soapObject.addProperty(entry.getKey(), new SoapPrimitive(
							SoapEnvelope.ENC, "base64Binary", data));
				} else {
					soapObject.addProperty(entry.getKey(), entry.getValue());
				}

			}
		}

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapSerializationEnvelope.VER11);
		envelope.bodyOut = soapObject;
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;
		envelope.setOutputSoapObject(soapObject);

		// 创建传输对象，将信封序列化对象远程传输，并请求服务
		HttpTransportSE transport = new HttpTransportSE(baseUrl);

		try {
			transport.call(soapAction, envelope);

			// System.out.println(envelope.bodyIn);
			SoapObject soap = (SoapObject) envelope.bodyIn;

			// System.out.println("soap==="+soap);
			SoapPrimitive p = (SoapPrimitive) soap.getProperty(0);
			// System.out.println("p===="+p);
			Object o = p.getValue();

			// System.out.println("o===>"+o);
			if (o != null) {
				return o;
			} else {
				return "";
			}
		} catch (HttpResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "exception";
	}

	public UserInfo parseUserInfo(String json, String pwd) {

		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(json);

			jsonObject = jsonObject.getJSONObject("data");
			UserInfo u = new UserInfo();
			u.setUsername(jsonObject.getString("username"));
			u.setUserphone(jsonObject.getString("userphone"));
			u.setPassword(pwd);
			u.setUserId(jsonObject.getString("userId"));
			return u;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public DealerBaseInfo parseBaseDealerInfo(String json, boolean flag) {

		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(json);

			// jsonObject = jsonObject.getJSONObject("table");

			JSONArray array = jsonObject.getJSONArray("table");

			jsonObject = array.getJSONObject(0);
			DealerBaseInfo d = new DealerBaseInfo();
			d.setNo(jsonObject.getString("no"));
			d.setId(jsonObject.getString("id"));
			d.setAddress(jsonObject.getString("address"));
			d.setCompname(jsonObject.getString("compname"));
			d.setComppeople(jsonObject.getString("comppeople"));
			d.setIntro(jsonObject.getString("intro"));
			d.setPort(jsonObject.getString("port"));
			d.setProvincecity(jsonObject.getString("provincecity"));
			d.setTelephone(jsonObject.getString("telephone"));
			d.setUserimg(jsonObject.getString("userimg"));
			if (flag) {
				d.setGuanzu(jsonObject.getString("guanzu"));
			}

			return d;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<DealerBaseInfo> parseDealerBaseInfoBySearch(String json) {

		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(json);

			// jsonObject = jsonObject.getJSONObject("table");

			JSONArray arrays = jsonObject.getJSONArray("table");

			ArrayList<DealerBaseInfo> all = new ArrayList<DealerBaseInfo>();
			for (int i = 0; i < arrays.length(); i++) {

				jsonObject = arrays.getJSONObject(i);
				DealerBaseInfo d = new DealerBaseInfo();
				d.setNo(jsonObject.getString("no"));
				d.setId(jsonObject.getString("id"));
				d.setCompname(jsonObject.getString("compname"));
				d.setIntro(jsonObject.getString("intro"));
				d.setUserimg(jsonObject.getString("userimg"));

				all.add(d);
			}

			return all;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<DealerBaseInfo> parseDealerAttention(String json) {

		JSONObject jsonObject = null;

		/*
		 * "no":"1", --序列ID "id": "183", --经销商ID "compname": "", --公司名称
		 * "comppeople": "", --公司负责人 "telephone": "", --负责人电话 "intro": "",
		 * --公司简介 "userimg": "" --
		 */
		try {
			jsonObject = new JSONObject(json);

			JSONArray arrays = jsonObject.getJSONArray("table");

			ArrayList<DealerBaseInfo> all = new ArrayList<DealerBaseInfo>();
			for (int i = 0; i < arrays.length(); i++) {

				jsonObject = arrays.getJSONObject(i);
				DealerBaseInfo d = new DealerBaseInfo();
				d.setNo(jsonObject.getString("no"));
				d.setId(jsonObject.getString("id"));
				d.setCompname(jsonObject.getString("compname"));
				d.setComppeople(jsonObject.getString("comppeople"));
				d.setTelephone(jsonObject.getString("telephone"));
				d.setIntro(jsonObject.getString("intro"));
				d.setUserimg(jsonObject.getString("userimg"));
				d.setAddress(jsonObject.getString("address"));

				all.add(d);
			}

			return all;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public EditCarInfo parseEditCarInfo(String json) {

		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(json);

			// jsonObject = jsonObject.getJSONObject("table");

			JSONArray array = jsonObject.getJSONArray("table");

			jsonObject = array.getJSONObject(0);
			EditCarInfo editInfo = new EditCarInfo();
			editInfo.setNo(jsonObject.getString("no"));
			editInfo.setId(jsonObject.getString("id"));
			editInfo.setName(jsonObject.getString("name"));
			editInfo.setAdddate(jsonObject.getString("adddate"));
			editInfo.setCompanyname(jsonObject.getString("companyname"));
			editInfo.setDdid(jsonObject.getString("ddid"));
			editInfo.setDealerid(jsonObject.getString("dealerid"));
			editInfo.setImg(jsonObject.getString("img"));
			editInfo.setLgid(jsonObject.getString("lgid"));
			editInfo.setLgname(jsonObject.getString("lgname"));
			editInfo.setNsid(jsonObject.getString("nsid"));
			editInfo.setNsname(jsonObject.getString("nsname"));
			editInfo.setPinpaiid(jsonObject.getString("pinpaiid"));
			editInfo.setPinpainame(jsonObject.getString("pinpainame"));
			editInfo.setPress(jsonObject.getString("press"));
			editInfo.setQhtime(jsonObject.getString("qhtime"));
			editInfo.setVin(jsonObject.getString("vin"));
			editInfo.setWsid(jsonObject.getString("wsid"));
			editInfo.setWsname(jsonObject.getString("wsname"));
			editInfo.setXhorqh(jsonObject.getString("xhorqh"));
			editInfo.setXilieid(jsonObject.getString("xilieid"));
			editInfo.setXiliename(jsonObject.getString("xiliename"));
			editInfo.setXppz(jsonObject.getString("xppz"));
			editInfo.setIshead(jsonObject.getString("ishead"));
			return editInfo;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
